package com.tc.biz.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tc.activiti.util.user.UserUtil;
import com.tc.base.constants.PageConstants;
import com.tc.base.constants.StateEnum;
import com.tc.base.entity.APIRequest;
import com.tc.base.entity.APIResult;
import com.tc.base.web.GenericController;
import com.tc.factory.CustomGroupEntityManager;
import com.tc.biz.entity.SysUser;
import com.tc.biz.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * @author zengqingfa
 * @date 2019/10/18 15:40
 * @description
 * @email zengqingfa_java@163.com
 */
@Api(tags = "人员管理", value = "人员管理")
@Controller
@RequestMapping("/user")
public class UserController extends GenericController {

    public static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    protected IUserService userService;

    // Activiti Identify Service  关于人员信息
    @Autowired
    protected IdentityService identityService;

    @Autowired
    protected CustomGroupEntityManager customGroupEntityManager;

    @ApiOperation(value = "查询所有人员", notes = "查询所有人员")
    @RequestMapping(value = "/findAll", method = RequestMethod.GET)
    @ResponseBody
    public APIResult<List<SysUser>> findAll() {
        APIResult<List<SysUser>> result = new APIResult<>();
        try {
            List<SysUser> userList = userService.findAll(); //获取后台数据列表
            result.setData(userList);
            result.setMessage("查询所有人员成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_PERSON.getCode());
            result.setMessage(StateEnum.ERROR_PERSON.getText());
            result.setCause(e.getMessage());
            logger.error("/user/findAll", e);
        }
        return result;
    }

    /**
     * 登录系统
     *
     * @param userName
     * @param password
     * @param session
     * @return
     */
    @ApiOperation(value = "登录", notes = "登录")
    @RequestMapping(value = "/logon", method = RequestMethod.GET)
    public String logon(@RequestParam("username") String userName, @RequestParam("password") String password, HttpSession session) {
        logger.debug("logon request: {username={}, password={}}", userName, password);
        boolean checkPassword = identityService.checkPassword(userName, password);
        if (checkPassword) {
            // read user from database
            User user = identityService.createUserQuery().userId(userName).singleResult();
            UserUtil.saveUserToSession(session, user);
            //  List<Group> groupList = identityService.createGroupQuery().groupMember(userName).list();
            List<Group> groupList = customGroupEntityManager.findGroupsByUser(userName);
            session.setAttribute("groups", groupList);
            String[] groupNames = new String[groupList.size()];
            for (int i = 0; i < groupNames.length; i++) {
                System.out.println(groupList.get(i).getName());
                groupNames[i] = groupList.get(i).getName();
            }
            session.setAttribute("groupNames", ArrayUtils.toString(groupNames));
            return "redirect:/main/index";
        } else {
            return "redirect:/login?error=true";
        }
    }

    @RequestMapping(value = "/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "/login";
    }

    @RequestMapping(value = "/login")
    public String login(HttpSession session) {
        return "login";
    }

    @ApiOperation(value = "人员分页列表", notes = "人员分页列表")
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    @ResponseBody
    public APIResult<PageInfo> findByPage(@RequestParam("currentPage") Integer pageNo, @RequestParam Integer pageSize,
                                          @RequestParam("searchVal") String searchVal) {
        APIResult<PageInfo> result = new APIResult<>();
        if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
        if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
        try {
            //使用分页插件
            PageHelper.startPage(pageNo, pageSize);
            //根据查询的数据列表，得到分页的结果对象
            List<SysUser> userList = userService.findByUsername(searchVal); //获取后台数据列表
            PageInfo pageInfo = new PageInfo(userList);
            result.setData(pageInfo);
            result.setMessage("查询人员成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_PERSON.getCode());
            result.setMessage(StateEnum.ERROR_PERSON.getText());
            result.setCause(e.getMessage());
            logger.error("/user/getUserList", e);
        }
        return result;
    }

    @ApiOperation(value = "通过用户名查询用户", notes = "通过用户名查询用户")
    @RequestMapping(value = "/getUserListByPage", method = RequestMethod.POST)
    @ResponseBody
    public APIResult<PageInfo> findUserListByPage(@RequestBody(required = true) APIRequest request, HttpServletRequest servletRequest) {
        APIResult<PageInfo> result = new APIResult<>();
        Integer pageSize = request.getRequestPage().getLimit();
        Integer pageNo = request.getRequestPage().getPageNo();
        if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
        if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
        String username = request.getParameter("username");//人名
        try {
            //使用分页插件
            PageHelper.startPage(pageNo, pageSize);
            List<SysUser> userList = userService.findByUsername(username); //获取后台数据列表
            //根据查询的数据列表，得到分页的结果对象
            PageInfo pageInfo = new PageInfo(userList);
            result.setData(pageInfo);
            result.setMessage("查询人员成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_PERSON.getCode());
            result.setMessage(StateEnum.ERROR_PERSON.getText());
            result.setCause(e.getMessage());
            logger.error("/user/getUserList", e);
        }
        return result;
    }



}
